package com.itcaius.myandroidhomework.data.repo;

import android.util.Log;

import com.itcaius.myandroidhomework.data.dao.UserDao;
import com.itcaius.myandroidhomework.data.entity.UserEntity;
import com.itcaius.myandroidhomework.data.callback.DatabaseCallback;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Created by itcaius on 2019/4/26.
 * TODO: 实现对应用户数据的管理，封装数据库操作
 */
public class UserRepository {
    private UserDao userDao;
    private Executor executor = Executors.newSingleThreadExecutor(); //使用单个后台线程

    public UserRepository(UserDao userDao){
        this.userDao = userDao;
    }

    //插入数据
    public void insertUser(UserEntity user){
        executor.execute(()->{
            try{
                userDao.insertUser(user);
            }catch (Exception e){
                Log.e("UserRepository","Error inserting user",e);
            }
        });
    }

    //删除数据
    public void deleteUser(UserEntity user){
        executor.execute(()-> {
            try{
                userDao.deleteUser(user);
            }catch (Exception e) {
                Log.e("UserRepository", "Error deleting user", e);
            }
        });
    }

    //更新数据
    public void updateUser(UserEntity user, DatabaseCallback<UserEntity> callback){
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try{
                    userDao.updateUser(user);
                    callback.onDataLoaded(user);
                }catch (Exception e){
                    Log.e("UserRepository","Error updating user",e);
                    callback.onError(e);
                }
            }
        });
    }

    //通过用户名获取信息
    public void getUser(String username, DatabaseCallback<UserEntity> callback){
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try{
                    UserEntity user = userDao.getUser(username);
                    callback.onDataLoaded(user);
                }catch(Exception e){
                    Log.e("UserRepository","Error getting user",e);
                    callback.onError(e);
                }
            }
        });
    }

    //查询所有用户
    public void getAllUsers(DatabaseCallback<List<UserEntity>> callback){
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try{
                    List<UserEntity> all = userDao.getAll();
                    callback.onDataLoaded(all);
                }catch (Exception e){
                    Log.e("UserRepository","Error getting all users",e);
                    callback.onError(e);
                }
            }
        });
    }
}
